#include "WS2812_Control.h"

#include "uart.h"
#include <string.h>
#include <stdlib.h>
#include <math.h>

WS2812_Controller ledStrip;

PowerState_enum powerState = EFFECT_OFF;

EffectType currentEffect = EFFECT_SINGLE_COLOR;
EffectType lastEffect = EFFECT_RAINBOW;

uint8_t effectSpeed = 50;            // 效果更新速度
uint8_t effectBrightness = 128;     // 效果亮度
uint8_t effectHue = 0;              // 效果色相
uint8_t effectSaturation = 255;     // 效果饱和度

uint16_t effectCounter = 0;

// 随机效果专用变量
uint8_t randomSeed = 0;
uint32_t lastRandomTime = 0;
uint8_t randomLedPositions[LED_COUNT]; // 存储随机LED位置
uint8_t randomLedCount = 0;             // 随机选择的LED数量

// 串口接收相关变量
uint8_t uart_rx_buffer[16];
uint16_t uart_rx_len = 0;

// 开关机操作
void powerOn(void)
{
    powerState = EFFECT_ON;
}

void powerOff(void)
{
    powerState = EFFECT_OFF;
}

// 设置当前效果
void setEffect(EffectType effect)   
{
    currentEffect = effect;
}

// 设置灯光亮度
void setBrightness(uint8_t brightness)
{
    if(currentEffect == EFFECT_SINGLE_COLOR)
    {
        if(brightness > 255)
        {
            brightness = 255;
        }
        effectBrightness = brightness;
    }
    
}

// 设置灯光更新速度
void setSpeed(uint8_t speed)
{
    if(currentEffect == EFFECT_SINGLE_COLOR)
    {
        if(speed >= 100)
        {
            speed = 99;
        }
        effectSpeed = speed;
    }
    
}

// 设置灯光色相
void setHue(uint8_t hue)
{
    if(currentEffect == EFFECT_SINGLE_COLOR)
    {
        if(hue > 255)
        {
            hue = 255;
        }
        effectHue = hue;
    }
    
}

// 设置灯光饱和度
void setSaturation(uint8_t saturation)
{
    effectSaturation = saturation;
}

// 获取灯光状态
uint8_t get_power(void)
{
    return powerState;
}

// 获取当前效果
uint8_t get_effect(void)
{
    return currentEffect;
}

uint8_t get_speed(void)
{
    return effectSpeed;
}

// 获取灯光亮度
uint8_t get_brightness(void)
{
    return effectBrightness;
}

// 获取灯光色相
uint8_t get_hue(void)
{
    return effectHue;
}

// 获取灯光饱和度
uint8_t get_saturation(void)
{
    return effectSaturation;
}

// 单纯色显示
void SingleColorEffect(void)
{
    uint32_t color = WS2812_HSVToColor(effectHue, effectSaturation, effectBrightness);

    for (uint16_t i = 0; i < ledStrip.led_count; i++)
    {
        WS2812_SetPixel(&ledStrip, i, color);
    }
    WS2812_Show(&ledStrip);
}

// 生成随机的LED位置
void generateRandomLedPositions(uint8_t count)
{
    if (count > LED_COUNT)
        count = LED_COUNT;
    randomLedCount = count;

    // 生成不重复的随机位置
    for (uint8_t i = 0; i < count; i++)
    {
        uint8_t pos;
        uint8_t duplicate;

        // 确保位置不重复
        do
        {
            duplicate = 0;
            pos = rand() % LED_COUNT;

            for (uint8_t j = 0; j < i; j++)
            {
                if (randomLedPositions[j] == pos)
                {
                    duplicate = 1;
                    break;
                }
            }
        } while (duplicate);

        randomLedPositions[i] = pos;
    }
}

// 根据当前效果类型更新显示
void updateEffects(void)
{
    if(powerState == EFFECT_OFF)
    {
        if(lastEffect != EFFECT_OFF_B)
        {
            WS2812_Clear(&ledStrip);
            WS2812_Show(&ledStrip);
            lastEffect = EFFECT_OFF_B;
        }
        return;
    }
    effectCounter++;

    switch (currentEffect)
    {
    case EFFECT_SINGLE_COLOR:
        SingleColorEffect();
        break;
    case EFFECT_RAINBOW:
        rainbowEffect();
        break;
    case EFFECT_BREATHING:
        breathingEffect();
        break;
    case EFFECT_RUNNING:
        runningEffect();
        break;
    case EFFECT_METEOR:
        meteorEffect();
        break;
    case EFFECT_RAINBOW_FLOW:
        rainbowFlowEffect();
        break;
    case EFFECT_RANDOM_FLASH:
        randomFlashEffect();
        break;
    case EFFECT_COLOR_TRANSITION:
        colorTransitionEffect();
        break;
    case EFFECT_SCAN:
        scanEffect();
        break;
    case EFFECT_RANDOM_SINGLE:
        randomSingleEffect();
        break;
    case EFFECT_RANDOM_BURST:
        randomBurstEffect();
        break;
    case EFFECT_RANDOM_CHASE:
        randomChaseEffect();
        break;
    default:
        break;
    }

    if(currentEffect != lastEffect) // 切换效果时，清除所有LED
    {
        lastEffect = currentEffect;
        WS2812_Clear(&ledStrip);
        effectCounter = 0;
    }

    // 发送数据到灯带
    WS2812_Show(&ledStrip);
}

// 新增：随机点亮单个LED效果
void randomSingleEffect(void)
{
    // 定期更新
    if (effectCounter % (5 - effectSpeed / 20) == 0)
    {
        // 清除所有LED
        // WS2812_Clear(&ledStrip); //不清除

        // 随机选择一个LED和颜色
        uint16_t pos = rand() % ledStrip.led_count;
        uint32_t color = WS2812_HSVToColor(rand() % 256, 255, 255);

        // 设置随机LED
        WS2812_SetPixel(&ledStrip, pos, color);
    }
}

// 新增：随机位置爆发闪烁效果
void randomBurstEffect(void)
{
    // 定期生成新的爆发点
    if (effectCounter % (10 - effectSpeed / 10) == 0)
    {
        // 随机选择2-5个LED
        uint8_t count = 2 + (rand() % 4);
        generateRandomLedPositions(count);

        // 随机选择一种颜色
        uint8_t hue = rand() % 256;

        // 为选中的LED设置随机亮度
        for (uint8_t i = 0; i < randomLedCount; i++)
        {
            uint8_t brightness = 100 + (rand() % 156); // 100-255
            WS2812_SetPixel(&ledStrip, randomLedPositions[i],
                            WS2812_HSVToColor(hue, 255, brightness));
        }
    }

    // 所有点亮的LED逐渐变暗
    for (uint16_t i = 0; i < ledStrip.led_count; i++)
    {
        uint32_t color = WS2812_GetPixel(&ledStrip, i);
        if (color != 0)
        {
            uint8_t r = (color >> 16) & 0xFF;
            uint8_t g = (color >> 8) & 0xFF;
            uint8_t b = color & 0xFF;

            // 快速衰减
            r = (r * 1) / 2;
            g = (g * 1) / 2;
            b = (b * 1) / 2;

            WS2812_SetPixel(&ledStrip, i, (r << 16) | (g << 8) | b);
        }
    }
}

// 新增：随机追逐效果
void randomChaseEffect(void)
{
    static uint16_t chasePositions[5] = {0};
    static uint8_t chaseColors[5] = {0};
    static uint8_t chaseLength = 3;

    // 定期更新追逐序列
    if (effectCounter % (3 - effectSpeed / 30) == 0)
    {
        // 清除所有LED
        WS2812_Clear(&ledStrip);

        // 随机调整追逐长度
        if (effectCounter % 20 == 0)
        {
            chaseLength = 2 + (rand() % 4); // 2-5个LED的追逐序列
        }

        // 移动追逐序列
        for (int8_t i = chaseLength - 1; i > 0; i--)
        {
            chasePositions[i] = chasePositions[i - 1];
            chaseColors[i] = chaseColors[i - 1];
        }

        // 随机生成新的头部位置和颜色
        chasePositions[0] = rand() % ledStrip.led_count;
        chaseColors[0] = rand() % 256;

        // 绘制追逐序列，尾部逐渐变暗
        for (uint8_t i = 0; i < chaseLength; i++)
        {
            uint8_t brightness = 255 - (i * 50);
            if (brightness > 255)
                brightness = 0;

            WS2812_SetPixel(&ledStrip, chasePositions[i],
                            WS2812_HSVToColor(chaseColors[i], 255, brightness));
        }
    }
}

// 新增：全随机模式（随机切换各种效果）
void randomAllEffect(void)
{
    // 该效果的逻辑在updateEffects中处理
}

// 彩虹效果
void rainbowEffect(void)
{
    for (uint16_t i = 0; i < ledStrip.led_count; i++)
    {
        uint8_t hue = (i * 4 + effectCounter) % 256;
        WS2812_SetPixel(&ledStrip, i, WS2812_HSVToColor(hue, 255, 255));
    }
}

// 呼吸灯效果
void breathingEffect(void)
{
    // 计算呼吸亮度 (0-255)
    uint8_t breathBrightness = (uint8_t)(127.5 * (1 + cos(effectCounter * 0.1))) *
                               (effectBrightness / 255.0);

    // 固定为蓝色
    uint32_t color = WS2812_HSVToColor(180, 255, breathBrightness);

    // 所有LED设置相同颜色
    for (uint16_t i = 0; i < ledStrip.led_count; i++)
    {
        WS2812_SetPixel(&ledStrip, i, color);
    }
}

// 流水灯效果
void runningEffect(void)
{
    // 清除所有LED
    WS2812_Clear(&ledStrip);

    // 计算当前点亮的LED位置
    uint16_t pos = (effectCounter / 2) % ledStrip.led_count;

    // 设置当前LED为红色
    WS2812_SetPixel(&ledStrip, pos, WS2812_HSVToColor(0, 255, 255));

    // 设置前一个LED为暗红色（尾迹）
    if (pos > 0)
    {
        WS2812_SetPixel(&ledStrip, pos - 1, WS2812_HSVToColor(0, 255, 100));
    }
    else if (ledStrip.led_count > 1)
    {
        WS2812_SetPixel(&ledStrip, ledStrip.led_count - 1, WS2812_HSVToColor(0, 255, 100));
    }
}

// 流星效果
void meteorEffect(void)
{
    static uint8_t trailLength = 5;
    static uint8_t lastMeteorPos = 0;

    // 逐渐变暗所有LED，模拟尾迹消失
    for (uint16_t i = 0; i < ledStrip.led_count; i++)
    {
        uint32_t color = WS2812_GetPixel(&ledStrip, i);
        if (color != 0)
        {
            // 降低亮度
            uint8_t r = (color >> 16) & 0xFF;
            uint8_t g = (color >> 8) & 0xFF;
            uint8_t b = color & 0xFF;

            r = (r * 3) / 4;
            g = (g * 3) / 4;
            b = (b * 3) / 4;

            WS2812_SetPixel(&ledStrip, i, (r << 16) | (g << 8) | b);
        }
    }

    // 定期生成新流星
    if (effectCounter % 10 == 0)
    {
        lastMeteorPos = (lastMeteorPos + ledStrip.led_count / 4) % ledStrip.led_count;
        uint8_t hue = (effectCounter / 20) % 256; // 缓慢变化流星颜色

        // 绘制流星头部和尾迹
        for (uint8_t i = 0; i < trailLength; i++)
        {
            int16_t pos = lastMeteorPos - i;
            if (pos < 0)
                pos += ledStrip.led_count;

            // 尾迹逐渐变暗
            uint8_t brightness = 255 - (i * 50);
            if (brightness > 255)
                brightness = 0;

            WS2812_SetPixel(&ledStrip, pos, WS2812_HSVToColor(hue, 255, brightness));
        }
    }
}

// 彩虹流动效果
void rainbowFlowEffect(void)
{
    for (uint16_t i = 0; i < ledStrip.led_count; i++)
    {
        uint8_t hue = (i * 2 + effectCounter * 2) % 256;
        WS2812_SetPixel(&ledStrip, i, WS2812_HSVToColor(hue, 255, 255));
    }
}

// 随机闪烁效果
void randomFlashEffect(void)
{
    // 随机点亮一些LED
    if (rand() % 5 == 0)
    { // 控制闪烁频率
        uint16_t pos = rand() % ledStrip.led_count;
        uint8_t hue = rand() % 256;
        WS2812_SetPixel(&ledStrip, pos, WS2812_HSVToColor(hue, 255, 255));
    }

    // 所有点亮的LED逐渐变暗
    for (uint16_t i = 0; i < ledStrip.led_count; i++)
    {
        uint32_t color = WS2812_GetPixel(&ledStrip, i);
        if (color != 0)
        {
            uint8_t r = (color >> 16) & 0xFF;
            uint8_t g = (color >> 8) & 0xFF;
            uint8_t b = color & 0xFF;

            // 指数衰减，熄灭更快
            r = (r * 2) / 3;
            g = (g * 2) / 3;
            b = (b * 2) / 3;

            WS2812_SetPixel(&ledStrip, i, (r << 16) | (g << 8) | b);
        }
    }
}

// 颜色渐变过渡效果
void colorTransitionEffect(void)
{
    static uint8_t startHue = 0;
    static uint8_t targetHue = 120;
    static uint16_t transitionStep = 0;
    static const uint16_t transitionLength = 50;

    // 计算当前颜色
    uint8_t currentHue;
    if (transitionStep >= transitionLength)
    {
        // 过渡完成，选择新的目标颜色
        startHue = targetHue;
        targetHue = rand() % 256;
        transitionStep = 0;
        currentHue = startHue;
    }
    else
    {
        // 计算过渡中的颜色
        int16_t hueDiff = targetHue - startHue;
        if (hueDiff < 0)
            hueDiff += 256;
        currentHue = (startHue + (hueDiff * transitionStep) / transitionLength) % 256;
        transitionStep++;
    }

    // 所有LED设置为当前过渡颜色
    uint32_t color = WS2812_HSVToColor(currentHue, 255, 255);
    for (uint16_t i = 0; i < ledStrip.led_count; i++)
    {
        WS2812_SetPixel(&ledStrip, i, color);
    }
}

// 扫描效果
void scanEffect(void)
{
    static int8_t direction = 1;
    static uint16_t scanPos = 0;

    // 清除所有LED
    WS2812_Clear(&ledStrip);

    // 计算扫描位置
    if (scanPos >= ledStrip.led_count - 1)
        direction = -1;
    if (scanPos <= 0)
        direction = 1;
    scanPos += direction * (effectSpeed / 50);
    if (scanPos >= ledStrip.led_count)
        scanPos = ledStrip.led_count - 1;

    // 设置扫描线颜色（随时间变化）
    uint8_t hue = (effectCounter / 5) % 256;

    // 绘制主扫描线
    WS2812_SetPixel(&ledStrip, scanPos, WS2812_HSVToColor(hue, 255, 255));

    // 绘制辅助线（两侧渐变）
    for (uint8_t i = 1; i <= 3; i++)
    {
        if (scanPos + i < ledStrip.led_count)
        {
            uint8_t brightness = 255 - (i * 60);
            WS2812_SetPixel(&ledStrip, scanPos + i, WS2812_HSVToColor(hue, 255, brightness));
        }
        if (scanPos - i >= 0)
        {
            uint8_t brightness = 255 - (i * 60);
            WS2812_SetPixel(&ledStrip, scanPos - i, WS2812_HSVToColor(hue, 255, brightness));
        }
    }
}

// 处理串口命令
void processUartCommand(void)
{
    uint16_t data_buf = 0;

    if (uart_rx_len == 0)
        return;
    if(uart_rx_buffer[0] == 'p' && uart_rx_len == 1)
    {
        // 开关机操作
        powerState = (powerState == EFFECT_OFF) ? EFFECT_ON : EFFECT_OFF;
        if(powerState == EFFECT_OFF)
        {
            HAL_UART_Transmit(&DebugUartHandle, (uint8_t *)"已关闭\r\n", 7, 100);
        }
        else
        {
            HAL_UART_Transmit(&DebugUartHandle, (uint8_t *)"已开启\r\n", 7, 100);
        }
        effectCounter = 0;  // 重置效果计数器
        lastRandomTime = 0; // 重置随机效果计时器
    }
    if(powerState == EFFECT_OFF)
    {
        return;
    }
   
    if(uart_rx_buffer[0] == 'h' && uart_rx_len >= 2)
    {
        if(currentEffect == EFFECT_SINGLE_COLOR)
        {
            data_buf = atoi((char *)&uart_rx_buffer[1]);
            if(data_buf <= 255)
            {
                effectHue = data_buf;
            }
            else
            {
                effectHue = 255;
            }
            HAL_UART_Transmit(&DebugUartHandle, (uint8_t *)"色相已更新\r\n", 11, 100);
        }
    }
    else if(uart_rx_buffer[0] == 's' && uart_rx_len >= 2)
    {
        data_buf = atoi((char *)&uart_rx_buffer[1]);
        if(data_buf <= 255)
        {
            effectSaturation = data_buf;
        }
        else
        {
            effectSaturation = 255;
        }
        HAL_UART_Transmit(&DebugUartHandle, (uint8_t *)"饱和度已更新\r\n", 11, 100);
    }
    else if(uart_rx_buffer[0] == 'v' && uart_rx_len >= 2)
    {
        data_buf = atoi((char *)&uart_rx_buffer[1]);
        if(data_buf <= 255)
        {
            effectBrightness = data_buf;
        }
        else
        {
            effectBrightness = 255;
        }
        HAL_UART_Transmit(&DebugUartHandle, (uint8_t *)"明度已更新\r\n", 11, 100);
    }
    else
    if (uart_rx_buffer[0] == 'e' && uart_rx_len >= 2)
    {
        // 设置效果
        uint8_t effect = atoi((char *)&uart_rx_buffer[1]);
        if (effect < EFFECT_COUNT-1)
        {
            currentEffect = (EffectType)effect;
            effectCounter = 0;  // 重置效果计数器
            lastRandomTime = 0; // 重置随机效果计时器
            HAL_UART_Transmit(&DebugUartHandle, (uint8_t *)"效果已更新\r\n", 11, 100);
        }
        else
        {
            HAL_UART_Transmit(&DebugUartHandle, (uint8_t *)"无效的效果编号\r\n", 14, 100);
        }
    }
    else if (uart_rx_buffer[0] == 'b' && uart_rx_len >= 2)
    {
        // 设置亮度
        uint8_t brightness = atoi((char *)&uart_rx_buffer[1]);
        effectBrightness = brightness;
        WS2812_SetBrightness(&ledStrip, brightness);
        HAL_UART_Transmit(&DebugUartHandle, (uint8_t *)"亮度已更新\r\n", 11, 100);
    }
    else if (uart_rx_buffer[0] == 's' && uart_rx_len >= 2)
    {
        // 设置速度
        uint8_t speed = atoi((char *)&uart_rx_buffer[1]);
        if (speed > 0 && speed <= 100)
        {
            effectSpeed = speed;
            HAL_UART_Transmit(&DebugUartHandle, (uint8_t *)"速度已更新\r\n", 11, 100);
        }
        else
        {
            HAL_UART_Transmit(&DebugUartHandle, (uint8_t *)"速度必须在1-100之间\r\n", 18, 100);
        }
    }
    else if (uart_rx_buffer[0] == 'n' && uart_rx_len == 1)
    {
        // 切换到下一个效果
        currentEffect = (EffectType)((currentEffect + 1) % EFFECT_COUNT);
        effectCounter = 0;  // 重置效果计数器
        lastRandomTime = 0; // 重置随机效果计时器
        HAL_UART_Transmit(&DebugUartHandle, (uint8_t *)"已切换到下一个效果\r\n", 18, 100);
    }
    else if (uart_rx_buffer[0] == 'r' && uart_rx_len == 1)
    {
        // 立即切换到随机效果
        currentEffect = (EffectType)(rand() % EFFECT_COUNT);
        effectCounter = 0;  // 重置效果计数器
        lastRandomTime = 0; // 重置随机效果计时器
        HAL_UART_Transmit(&DebugUartHandle, (uint8_t *)"已切换到随机效果\r\n", 18, 100);
    }
    else if (uart_rx_buffer[0] == 'h' && uart_rx_len == 1)
    {
        // 帮助信息（更新了新效果）
        const char *help = "命令帮助:\r\n"
                           "e[数字] - 设置效果(0-11)\r\n"
                           "  0:自定义 1:彩虹 2:呼吸 3:流水 4:流星\r\n"
                           "  5:彩虹流动 6:随机闪烁 7:颜色过渡 8:扫描\r\n"
                           "  9:随机单点 10:随机爆发 11:随机追逐\r\n"
                           "b[数字] - 设置亮度(0-255)\r\n"
                           "s[数字] - 设置速度(1-100)\r\n"
                           "n - 切换到下一个效果\r\n"
                           "r - 随机选择一个效果\r\n"
                           "h - 显示帮助信息\r\n";
        HAL_UART_Transmit(&DebugUartHandle, (uint8_t *)help, strlen(help), 100);
    }
    else
    {
        HAL_UART_Transmit(&DebugUartHandle, (uint8_t *)"未知命令，输入h查看帮助\r\n", 24, 100);
    }

    // 清空接收缓冲区
    uart_rx_len = 0;
    memset(uart_rx_buffer, 0, sizeof(uart_rx_buffer));
}

// UART接收完成回调函数
void HAL_UART_RxCpltCallback(UART_HandleTypeDef *huart)
{
    if (huart->Instance == USART2)
    {
        // 检查是否收到回车或换行符，表示命令结束
        if (uart_rx_buffer[uart_rx_len] == '\r' || uart_rx_buffer[uart_rx_len] == '\n')
        {
            processUartCommand();
            memset(uart_rx_buffer, 0, sizeof(uart_rx_buffer));
            uart_rx_len = 0;
        }
        else
        {
            // 继续接收下一个字符
            uart_rx_len++;
            if (uart_rx_len >= sizeof(uart_rx_buffer))
            {
                uart_rx_len = 0; // 防止缓冲区溢出
                memset(uart_rx_buffer, 0, sizeof(uart_rx_buffer));
            }
        }

        // 重新启动接收中断
        HAL_UART_Receive_IT(&DebugUartHandle, &uart_rx_buffer[uart_rx_len], 1);
    }
}

// SPI发送完成回调函数
void HAL_SPI_TxCpltCallback(SPI_HandleTypeDef *hspi)  // 这里更改为DMA传输完成回调
{
    // 可以在这里添加发送完成后的处理
    if (hspi->Instance == SPI1)
    {
        ledStrip.is_transmitting = 0;
    }
}
